package com.example.comment.service.impl;

import com.example.comment.dao.ReviewMapper;
import com.example.comment.pojo.Review;
import com.example.comment.service.ReviewService;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author lenovo
 */
@Service
@Log4j2
public class ReviewServiceImpl implements ReviewService {
    @Autowired
    ReviewMapper reviewRepository;
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public List<Review> findAllReview() {
        return reviewRepository.findAll();
    }

    @Override
    public List<Review> findReviewByName(String username) {
        Query query = Query.query(Criteria.where("username").is(username));
        return mongoTemplate.find(query, Review.class);
    }

    @Override
    public List<Review> findReviewQueryByName(String username) {
        Query query = Query.query(Criteria.where("username").regex(username));
        return mongoTemplate.find(query, Review.class);
    }

    @Override
    public Review addReview(Review review) {
        return mongoTemplate.save(review);
    }

    @Override
    public UpdateResult updateReview(Review review) {
        Query query = Query.query(Criteria.where("username").is(review.getUsername()));
        List<Review> list = mongoTemplate.find(query, Review.class);
        log.info("===>{}----------------------",list);
        Update update = new Update();
        update.set("username",review.getUsername());
        update.set("sex",review.getSex());
        update.set("password",review.getPassword());
        update.set("number",review.getNumber());
        UpdateResult result = mongoTemplate.updateFirst(query,update,"review");
        return result;
    }

    @Override
    public DeleteResult deleteReviewByName(String username) {
        Query query = Query.query(Criteria.where("username").is(username));
        return mongoTemplate.remove(query,Review.class);
    }

}
